Spring Cloud—十、使用Spring Cloud Config统一管理微服务
10.1、Spring Cloud Config简介
Spring Cloud Config为分布式系统外部化配置提供了服务器和客户端的支持,它包括Config Server和Config Client两部分。由于Config Server和Config Client都实现了对Spring Environment和PropertySource抽象的映射,因此,Spring Cloud Config非常合适Spring应用程序,当然也可与任何其他语言编写的应用程序配合使用。
Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。
Config Client是Config Server的客户端,用于操作存储在Config Server中的配置内容。微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器。
使用Spring Cloud Config的架构:
10.2、快速入门-搭建Config Server
10.2.1、准备3个配置文件,推送git服务器
准备3个文件:
- demo-dev.properties
- demo-production.properties
- demo-test.properties
该文件的命名规则是:{application}-{profile}.properties
其内容是(另外2个文件内容稍有不同即可):1
2
3
4jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/demo?userUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
推送到git服务器,这里使用github。
10.2.2、创建工程springcloud-demo-config
pom依赖1
2
3
4<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
10.2.3、再启动类上增加注解@EnableConfigServer
10.2.4、编写application.properties
1 | server.port=9999 |
10.2.5、启动测试
测试已经看到配置文件的内容。
请求配置文件的规则如下:
/{application}/{profile}/[label]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
其中{label}是指分支,默认是master。
10.3、快速入门-搭建Config Client
我们再springclouf-demo-item项目中添加Config Client的支持。来读取JDBC的配置文件的内容。
10.3.1、导入依赖
1 | <dependency> |
10.3.2、创建配置文件boostrap.properties
1 | #对应的配置服务中的引用名称 |
10.3.3、编写JdbcConfigBean
1 | package cn.zuoqy.springclouddemoitem.config; |
10.3.4、编写测试方法进行测试
再ItemController中编写test方法1
2
3
4
5
6
7@Autowired
private JdbcConfigBean jdbcConfigBean;
@GetMapping(value = "test")
public String test() {
return this.jdbcConfigBean.toString();
}
10.3.5、启动测试
测试结果显示已经从Config Server中获取到配置文件的内容。
10.4、手动更新运行中的配置文件
10.4.1、再springcloud-demo-item项目中加入依赖
1 | <dependency> |
10.4.2、为JdbcConfigBean添加@RefreshScope
10.4.3、再application.properties加上
1 | #是否开启actuator安全认证 |
10.4.4、post请求/refresh来更新配置内容:
10.4.5、测试结果
发现可以更新配置信息。
10.5、借助与git的webhook(web钩子)实现自动跟新
github等git服务器提供了web hook功能:再仓库中的资源发生更新时会通知给谁,这里的谁是一个url地址。
添加完成接下来测试发现,配置文件内容会动态更到Bean中。
10.6、Config Client配置的优化
10.6.1、再springcloud-demo-config中添加Eureka的依赖
1 | <dependency> |
10.6.2、再application.properties文件中增加
1 | #是否将自己注册到Eureka服务中,默认为true |
10.6.3、再启动类中增加注解@EnableDiscoveryClient注解
10.6.4、重新启动
可以看到再Eureka中已经又配置中心得服务
10.6.5、再springcloud-demo-item中修改bootstrap.properties配置
这里配置Eureka信息,因为Spring boot中bootstrap再application之前加载。
10.6.6、测试
出自:zuoqy博客
如若转载请注明出处!